const chunkSize = 5 * 1024 * 1024; // 切片大小为5M

/**
 * @description:
 * @param fileName 文件名
 * @param blob 下载的对象
 * @author: Zhu_liangyu
 */
export function downloadFile(response: any, fileName?: string) {
  const downloadElement = document.createElement("a");
  const href = window.URL.createObjectURL(response.data);
  if (!fileName) {
    let contentDisposition = response.headers["content-disposition"];
    let patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
    let result = patt.exec(contentDisposition) || [];
    let filename = decodeURI(result[1]);
    fileName = filename.replace(/\"/g, "");
  }
  downloadElement.style.display = "none";
  downloadElement.href = href;
  downloadElement.download = fileName;
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
  window.URL.revokeObjectURL(href);
}
/**
 * @description: 文件流下载文件
 * @param {string} fileName 文件名
 * @param {Blob} blob 文件流
 */
export function downloadBlobFile(fileName: string, blob: Blob) {
  const elink = document.createElement("a");
  elink.download = fileName;
  elink.style.display = "none";
  let binaryData = [];
  binaryData.push(blob);
  elink.href = window.URL.createObjectURL(new Blob(binaryData));
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href); // 释放URL 对象
  document.body.removeChild(elink);
}

/**
 * 是否为大文件
 * @param file 文件
 */
export function isBigFile(file: File) {
  return file.size > chunkSize;
}

/**
 * 将文件进行分片上传
 * @param file 文件
 * @param size 分片文件大小
 * @returns
 */
export function createFileChunk(file: File, size = chunkSize) {
  const fileChunkList: Blob[] = [];
  let count = 0;
  while (count < file.size) {
    fileChunkList.push(file.slice(count, count + size));
    count += size;
  }
  return fileChunkList;
}
